package top.system.dept.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;

/**
 * @ClassName: HttpsFilter
 * @Author: Amosen
 * @Since: 2021/5/22
 */

// HTTPS过滤器，解决SpringBoot在重定向到443端口后，POST方法变为GET方法
//@WebFilter("/*")
public class HttpsFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(HttpsFilter.class);

    private static final String HTTPS = "https";

    private static final int HTTPS_PORT = 8443;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.info("进入HttpsFilter");

        URL newUrl = null;

        if (request.getScheme().equals(HTTPS)) {
            chain.doFilter(request, response);
        } else {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            String queryString = httpRequest.getQueryString() == null ? "" : "?" + httpRequest.getQueryString();
            httpResponse.setStatus(307);
            String requestUrl = httpRequest.getRequestURL().toString();
            URL reqUrl = new URL(requestUrl + queryString);
            newUrl = new URL(HTTPS, reqUrl.getHost(), HTTPS_PORT, reqUrl.getFile());
            // 进行重定向
            httpResponse.setHeader("Location", newUrl.toString());
            httpResponse.setHeader("Connection", "close");
            httpResponse.addHeader("Access-Control-Allow-Origin", "*");

        }
    }
}
